package com.xxl.job.executor.service.jobhandler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.test.LoginDevice;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.dao.YhkqbMapper;
import com.xxl.job.executor.model.Yhkqb;

import Acs.Kqlsgl;

import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

/**
 * XxlJob开发示例（Bean模式）
 *
 * 开发步骤： 1、任务开发：在Spring Bean实例中，开发Job方法； 2、注解配置：为Job方法添加注解
 * "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy =
 * "JobHandler销毁方法")"，注解value值对应的是调度中心新建任务的JobHandler属性的值。 3、执行日志：需要通过
 * "XxlJobHelper.log" 打印执行日志； 4、任务结果：默认任务结果为 "成功"
 * 状态，不需要主动设置；如有诉求，比如设置任务结果为失败，可以通过 "XxlJobHelper.handleFail/handleSuccess"
 * 自主设置任务结果；
 *
 * @author xuxueli 2019-12-11 21:52:51
 */
@Component
public class SampleXxlJob {
	private static Logger logger = LoggerFactory.getLogger(SampleXxlJob.class);

	@Resource
	YhkqbMapper yhkqbManager;
	/**
	 * 1、简单任务示例（Bean模式）
	 */
	@XxlJob("kaoqingIpJobHandler")
	public void kaoqingIpJobHandler() throws Exception {
		XxlJobHelper.log("XXL-JOB, Hello World.");
//		String sql="select COUNT(1) from yhkqb";
		String sql="SELECT * FROM zz_test";

//		Object yhkqblist=  yhkqbManager.querySql(sql);
String kqrq,gh;
int i=0;
		List<Map> list = yhkqbManager.querySql(sql);
		for ( i = 0; i < list.size(); i++) {

			Map json = list.get(i);
			kqrq = json.get("kqrq").toString();
			Date d=(Date)json.get("xbdk2");
			gh = json.get("gh").toString();


		}
 
		Yhkqb yhkqb=yhkqbManager.selectByPrimaryKey("428032457129852929");
		List yhkqblis1=  yhkqbManager.query("9990006474","2021-09-12");
		if(yhkqb.getId()!=null)
			yhkqbManager.updateByPrimaryKey(yhkqb);
		else
			yhkqbManager.insert(yhkqb);
 		long num=yhkqbManager.countByExample(null);
		for ( i = 0; i < 5; i++) {
			XxlJobHelper.log("beat at:" + i);
			TimeUnit.SECONDS.sleep(2);
		}
		// default success
	}

	/**
	 * 2、分片广播任务
	 */
	@XxlJob("shardingJobHandler")
	public void shardingJobHandler() throws Exception {

		// 分片参数
		int shardIndex = XxlJobHelper.getShardIndex();
		int shardTotal = XxlJobHelper.getShardTotal();

		XxlJobHelper.log("分片参数：当前分片序号 = {}, 总分片数 = {}", shardIndex, shardTotal);

		// 业务逻辑
		for (int i = 0; i < shardTotal; i++) {
			if (i == shardIndex) {
				XxlJobHelper.log("第 {} 片, 命中分片开始处理", i);
			} else {
				XxlJobHelper.log("第 {} 片, 忽略", i);
			}
		}

	}

	/**
	 * 3、命令行任务
	 */
	@XxlJob("commandJobHandler")
	public void commandJobHandler() throws Exception {
		String command = XxlJobHelper.getJobParam();
		int exitValue = -1;

		BufferedReader bufferedReader = null;
		try {
			// command process
			ProcessBuilder processBuilder = new ProcessBuilder();
			processBuilder.command(command);
			processBuilder.redirectErrorStream(true);

			Process process = processBuilder.start();
			// Process process = Runtime.getRuntime().exec(command);

			BufferedInputStream bufferedInputStream = new BufferedInputStream(process.getInputStream());
			bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));

			// command log
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				XxlJobHelper.log(line);
			}

			// command exit
			process.waitFor();
			exitValue = process.exitValue();
		} catch (Exception e) {
			XxlJobHelper.log(e);
		} finally {
			if (bufferedReader != null) {
				bufferedReader.close();
			}
		}

		if (exitValue == 0) {
			// default success
		} else {
			XxlJobHelper.handleFail("command exit value(" + exitValue + ") is failed");
		}

	}

	/**
	 * 4、跨平台Http任务 参数示例： "url: http://www.baidu.com\n" + "method: get\n" + "data:
	 * content\n";
	 */
	@XxlJob("httpJobHandler")
	public void httpJobHandler() throws Exception {

		// param parse
		String param = XxlJobHelper.getJobParam();
		if (param == null || param.trim().length() == 0) {
			XxlJobHelper.log("param[" + param + "] invalid.");

			XxlJobHelper.handleFail();
			return;
		}

		String[] httpParams = param.split("\n");
		String url = null;
		String method = null;
		String data = null;
		for (String httpParam : httpParams) {
			if (httpParam.startsWith("url:")) {
				url = httpParam.substring(httpParam.indexOf("url:") + 4).trim();
			}
			if (httpParam.startsWith("method:")) {
				method = httpParam.substring(httpParam.indexOf("method:") + 7).trim().toUpperCase();
			}
			if (httpParam.startsWith("data:")) {
				data = httpParam.substring(httpParam.indexOf("data:") + 5).trim();
			}
		}

		// param valid
		if (url == null || url.trim().length() == 0) {
			XxlJobHelper.log("url[" + url + "] invalid.");

			XxlJobHelper.handleFail();
			return;
		}
		if (method == null || !Arrays.asList("GET", "POST").contains(method)) {
			XxlJobHelper.log("method[" + method + "] invalid.");

			XxlJobHelper.handleFail();
			return;
		}
		boolean isPostMethod = method.equals("POST");

		// request
		HttpURLConnection connection = null;
		BufferedReader bufferedReader = null;
		try {
			// connection
			URL realUrl = new URL(url);
			connection = (HttpURLConnection) realUrl.openConnection();

			// connection setting
			connection.setRequestMethod(method);
			connection.setDoOutput(isPostMethod);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setReadTimeout(5 * 1000);
			connection.setConnectTimeout(3 * 1000);
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
			connection.setRequestProperty("Accept-Charset", "application/json;charset=UTF-8");

			// do connection
			connection.connect();

			// data
			if (isPostMethod && data != null && data.trim().length() > 0) {
				DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
				dataOutputStream.write(data.getBytes("UTF-8"));
				dataOutputStream.flush();
				dataOutputStream.close();
			}

			// valid StatusCode
			int statusCode = connection.getResponseCode();
			if (statusCode != 200) {
				throw new RuntimeException("Http Request StatusCode(" + statusCode + ") Invalid.");
			}

			// result
			bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			StringBuilder result = new StringBuilder();
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				result.append(line);
			}
			String responseMsg = result.toString();

			XxlJobHelper.log(responseMsg);

			return;
		} catch (Exception e) {
			XxlJobHelper.log(e);

			XxlJobHelper.handleFail();
			return;
		} finally {
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
				if (connection != null) {
					connection.disconnect();
				}
			} catch (Exception e2) {
				XxlJobHelper.log(e2);
			}
		}

	}

	/**
	 * 5、生命周期任务示例：任务初始化与销毁时，支持自定义相关逻辑；
	 */
	@Resource // 自动注入，spring boot会帮我们实例化一个对象
	private JdbcTemplate commonDao; // 一个通过JDBC连接数据库的工具类，可以通过这个工具类对数据库进行增删改查

	@XxlJob(value = "demoJobHandler2", init = "init", destroy = "destroy")
	public void demoJobHandler2() throws Exception {
		XxlJobHelper.log("XXL-JOB, Hello World.");
		String m_sUsername = "admin";// 设备用户名
		String m_sPassword = "1234567a";// 设备密码
		short wport = 8000;
		String fromTime = "2021-06-02 00:00:00";
		String toTime = "2021-09-03 12:00:00";
		String ip = "192.168.1.107";
		String recodetime = "";
		try {

			List<Map<String, Object>> deviceList = commonDao.queryForList("select * from kqsbgl where sfyx =1 and tbsj >( NOW()- INTERVAL 20 MINUTE)");
			Map device = null;
//			while(true) {
			LoginDevice treat = new LoginDevice();

			for (int i = 0; i < deviceList.size(); i++) {
				try {

					device = deviceList.get(i);
//					deviceList.remove(0);

					Object obj = device.get("zhkqsj");
//				String sbid = (String) device.get("id_");
					ip = (String) device.get("ip");
System.out.println(i+"---------------------------"+ip);
//					Calendar calendar = Calendar.getInstance();
					if (obj != null)
						fromTime = obj.toString().replace(".0", "");
					else
						fromTime = new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date().getTime());
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					if (format.parse(fromTime).getTime() > new Date().getTime()-60000)
						continue;

					String currtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date().getTime());

//				LoginDevice treat = new LoginDevice();
//				 fromTime = "2021-06-02 00:00:00";
//				 toTime = "2021-09-03 12:00:00";
//				 ip = "192.168.1.107";
					List<Kqlsgl> list2 = null;

					try {
						list2 = treat.treatDevice(ip, m_sUsername, m_sPassword, wport, fromTime, currtime);
						if (list2 == null)
							continue;
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						continue;
					}
					if (list2.size() == 0)
						continue;
					int ii = 0;// 从切换班开始调试

					String mSql = "";
					Kqlsgl temp;
					int count = 0;

					for (; ii < list2.size(); ii++) {
						temp = list2.get(ii);

						if (list2.get(ii).getGh() == null)
							continue;

						recodetime = temp.getSj();
						if (count == 10) {
							mSql = "insert into sbxxsj (id_,sbip,gh,kqsj,seq,dqsj) values " + mSql;
							commonDao.execute(mSql);
							mSql = "";
							count = 0;
						} else
							count++;
						/*
						 * 插入数据库 1、拼接sql，每10条数据一条sql语句执行存储
						 */
						if (mSql != "")
							mSql += ",";
						mSql += "('" + currtime + "-" + temp.getGh() + ii + "','" + ip + "','" + temp.getGh() + "','"
								+ temp.getSj() + "'," + ii + ",'" + currtime + "')";
					}
					mSql = "insert into sbxxsj (id_,sbip,gh,kqsj,seq,dqsj) values " + mSql;
					commonDao.execute(mSql);
					// 记录日志
					String endtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime());

//					mSql = "insert into kqsblog (id_,sbip,kszxsj,jszxsj,sjjzsj,jls) values ('" + currtime + ip + "','"
//							+ ip + "','" + currtime + "','" + endtime + "','" + recodetime + "','" + list2.size()
//							+ "')";
//
//					commonDao.execute(mSql);
					// 保存打卡时间
					mSql = "update kqsbgl set zhkqsj='" + recodetime + "',tbsj='" + endtime + "' where ip='" + ip + "'";
					commonDao.execute(mSql);
					XxlJobHelper
							.log("ip:" + ip + " fromtime:" + fromTime + " list count:" + list2.size() + "sql:" + mSql);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					continue;
				}
			}
//			Thread.sleep(300000);
//			}
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}

		
		
		
	}

	public void init() {
		logger.info("init");
	}

	public void destroy() {
		logger.info("destory");
	}

}
